package com.chenfy.everysound.base

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.collection.SparseArrayCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide

/**
 * Created by 陈丰尧 on 12/31/20
 * RecyclerView的ViewHolder
 */
class BaseVH(resLayout: Int, parent: ViewGroup) :
    RecyclerView.ViewHolder(
        LayoutInflater.from(parent.context)
            .inflate(resLayout, parent, false)
    ) {
    val context: Context = parent.context
    private val views = SparseArrayCompat<View>()
    private var lastViewId = View.NO_ID

    fun <T : View> getView(viewId: Int): T {
        if (viewId == View.NO_ID) {
            throw IllegalArgumentException("请先调用getView方法,或其他set方法指定id")
        }
        lastViewId = viewId
        var view = views[viewId]
        view?.let {
            return view as T
        } ?: run {
            view = itemView.findViewById(viewId)
            views.put(viewId, view)
            return view as T
        }
    }

    fun setText(text: String, viewId: Int = lastViewId): BaseVH {
        val textView: TextView = getView(viewId)
        textView.text = text
        return this
    }

    fun setTextColor(colorStr: String, viewId: Int = lastViewId): BaseVH {
        val textView: TextView = getView(viewId)
        textView.setTextColor(Color.parseColor(colorStr))
        return this
    }

    fun setTextSize(unit: Int, size: Float, viewId: Int = lastViewId): BaseVH {
        val textView: TextView = getView(viewId)
        textView.setTextSize(unit, size)
        return this
    }

    fun setImg(url: String, viewId: Int = lastViewId): BaseVH {
        val imageView: ImageView = getView(viewId)
        Glide.with(itemView)
            .load(url)
            .into(imageView)
        return this
    }

    fun setImgResource(imgResource: Int, viewId: Int = lastViewId): BaseVH {
        val imageView: ImageView = getView(viewId)
        imageView.setImageResource(imgResource)
        return this
    }

    fun setImgDrawable(drawable: Drawable, viewId: Int = lastViewId): BaseVH {
        val imageView: ImageView = getView(viewId)
        imageView.setImageDrawable(drawable)
        return this
    }

    fun setImgLevel(level: Int, viewId: Int = lastViewId): BaseVH {
        val imageView: ImageView = getView(viewId)
        val drawable = imageView.drawable
        if (drawable != null) {
            drawable.level = level
        }
        return this
    }

    fun visible(visible: Boolean, viewId: Int = lastViewId): BaseVH {
        val view: View = getView(viewId)
        view.visibility = if (visible) View.VISIBLE else View.GONE
        return this
    }
}